package com.lottery.material.controller.admin.article;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.pojo.article.ArticleChargePricingConfig;
import com.lottery.material.pojo.conf.UserLevelDict;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojocustom.article.ArticleChargePricingConfigCustom;
import com.lottery.material.service.admin.article.ArticleChargePricingConfigService;
import com.lottery.material.service.admin.conf.UserLevelDictService;
import com.lottery.material.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * Description：文章收费定价配置Controller
 * Created by 朱正磊 on 2019-04-13 20:14
 */
@Controller("adminArticleChargePricingConfigController")
@RequestMapping("/admin/articleChargePricingConfig")
public class ArticleChargePricingConfigController extends BaseController {

    //菜单地址，用于权限控制
    private String menuUrl = "admin/articleChargePricingConfig/list";

    private final ArticleChargePricingConfigService articleChargePricingConfigService;

    private final UserLevelDictService userLevelDictService;

    @Autowired
    public ArticleChargePricingConfigController(ArticleChargePricingConfigService articleChargePricingConfigService,
                                                UserLevelDictService userLevelDictService) {
        this.articleChargePricingConfigService = articleChargePricingConfigService;
        this.userLevelDictService = userLevelDictService;
    }

    /**
     * description：分页列表
     * user 朱正磊
     * time 2019-04-17 15:06
     * @param page 分页对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/list")
    public ModelAndView listPage(Page page, Map<String, Object> map) {
        //分页对象设置页面请求参数
        PageData pd = getPageData();
        PdUtil.rePut(pd);
        page.setPd(pd);

        //查询分页列表
        List<ArticleChargePricingConfigCustom> list = articleChargePricingConfigService.findCustomListPage(page);
        map.put("list", list);
        map.put("pd", pd);
        map.put("QX", Jurisdiction.getHC());

        return new ModelAndView("article/articleChargePricingConfig/listPage", map);
    }

    /**
     * description：详情页面
     * user 朱正磊
     * time 2019-04-17 16:20
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/detailPage")
    public ModelAndView detailPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {//判断是否有查看权限
            return null;
        }

        //根据主键查询扩展类
        ArticleChargePricingConfigCustom articleChargePricingConfig = articleChargePricingConfigService.findCustomById(id);
        map.put("articleChargePricingConfig", articleChargePricingConfig);

        return new ModelAndView("article/articleChargePricingConfig/detailPage", map);
    }

    /**
     * description：添加页面
     * user 朱正磊
     * time 2019-04-17 16:26
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/addPage")
    public ModelAndView addPage(Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {//判断是否有添加权限
            return null;
        }

        //用户等级（如果有的用户等级已经配置过文章收费定价配置了就排除掉）
        List<UserLevelDict> userLevelDictList = userLevelDictService.findAll();
        Iterator<UserLevelDict> iterator = userLevelDictList.iterator();
        while (iterator.hasNext()) {
            UserLevelDict levelDict = iterator.next();
            Integer userLevel = levelDict.getUserLevel();
            ArticleChargePricingConfig config = articleChargePricingConfigService.findByUserLevel(userLevel);
            if (AssertUtil.isNotEmpty(config)) {
                iterator.remove();
            }
        }
        map.put("userLevelDictList", userLevelDictList);

        //添加请求地址
        map.put("actionUrl", "admin/articleChargePricingConfig/add");

        return new ModelAndView("article/articleChargePricingConfig/addPage", map);
    }

    /**
     * description：添加（批量）
     * user 朱正磊
     * time 2019-04-17 16:39
     * @param articleChargePricingConfig 对象
     * @param map 响应数据Map
     * @param userLevels 用户等级数组
     * @return 返回模型视图
     */
    @RequestMapping("/add")
    public ModelAndView add(ArticleChargePricingConfig articleChargePricingConfig, Map<String, Object> map, Integer[] userLevels) {
        Integer flag = articleChargePricingConfigService.addBatch(articleChargePricingConfig, userLevels);
        if (Objects.equals(flag, 0)) { //添加失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //根据主键查询扩展类
        ArticleChargePricingConfigCustom articleChargePricingConfig = articleChargePricingConfigService.findCustomById(id);
        map.put("articleChargePricingConfig", articleChargePricingConfig);

        //用户等级（如果有的用户等级已经配置过文章收费定价配置了就排除掉）（修改页面其实不需要该数据，暂时留着吧）
        List<UserLevelDict> userLevelDictList = userLevelDictService.findAll();
        Iterator<UserLevelDict> iterator = userLevelDictList.iterator();
        while (iterator.hasNext()) {
            UserLevelDict levelDict = iterator.next();
            Integer userLevel = levelDict.getUserLevel();
            if (!Objects.equals(userLevel, articleChargePricingConfig.getUserLevel())) {
                ArticleChargePricingConfig config = articleChargePricingConfigService.findByUserLevel(userLevel);
                if (AssertUtil.isNotEmpty(config)) {
                    iterator.remove();
                }
            }
        }
        map.put("userLevelDictList", userLevelDictList);

        //修改请求地址
        map.put("actionUrl", "admin/articleChargePricingConfig/edit");

        return new ModelAndView("article/articleChargePricingConfig/editPage", map);
    }

    /**
     * description：修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param articleChargePricingConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/edit")
    public ModelAndView edit(ArticleChargePricingConfig articleChargePricingConfig, Map<String, Object> map) {
        Integer flag = articleChargePricingConfigService.updateById(articleChargePricingConfig);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：验证是否允许新增，如果所有的用户等级都配置了文章收费定价配置就不再允许新增数据
     * user 朱正磊
     * time 2019-05-20 13:21
     * @return 返回响应对象
     */
    @RequestMapping("/validateAdd")
    @ResponseBody
    public ResponseResult validateAdd() {
        boolean flag = true;//默认所有的用户等级都配置了文章收费定价配置
        //查询所有的用户等级字典数据
        List<UserLevelDict> userLevelDictList = userLevelDictService.findAll();
        //循环遍历用户等级字典列表
        for (UserLevelDict userLevelDict : userLevelDictList) {
            Integer userLevel = userLevelDict.getUserLevel();
            ArticleChargePricingConfig config = articleChargePricingConfigService.findByUserLevel(userLevel);
            if (AssertUtil.isEmpty(config)) {
                flag = false;//发现有一个用户等级没有配置文章收费定价配置
                break;
            }
        }
        if (flag) {
            return ResponseResult.buildResult(200);//不允许新增
        } else {
            return ResponseResult.buildResult(400);//允许新增
        }
    }

    /**
     * description：批量修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param ids 主键以,拼接的字符串
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editBatchPage")
    public ModelAndView editBatchPage(String ids, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //获取批量用户等级名称并回显
        List<Integer> idList = ListUtil.getIdList(ids);
        List<ArticleChargePricingConfig> configList = articleChargePricingConfigService.findByIds(idList);
        StringBuilder userLevelNames = new StringBuilder();
        for (int i = 0; i < configList.size(); i++) {
            ArticleChargePricingConfig config = configList.get(i);
            Integer userLevel = config.getUserLevel();
            String userLevelName = "V" + userLevel;
            if (i == 0) {
                userLevelNames = new StringBuilder(userLevelName);
            } else {
                userLevelNames.append(", ").append(userLevelName);
            }
        }
        map.put("userLevelNames", userLevelNames.toString());

        //回显批量主键
        map.put("ids", ids);

        //修改请求地址
        map.put("actionUrl", "admin/articleChargePricingConfig/editBatch");

        return new ModelAndView("article/articleChargePricingConfig/editBatchPage", map);
    }

    /**
     * description：批量修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param ids 主键以,拼接的字符串
     * @param minimumPrice 最低价格
     * @param maximumPrice 最高价格
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editBatch")
    public ModelAndView editBatch(String ids, Integer minimumPrice, Integer maximumPrice, Map<String, Object> map) {
        Integer flag = articleChargePricingConfigService.updateByIds(ids, minimumPrice, maximumPrice);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

}
